package com.bird.thread.base.background;

/**
 * @author sijunqiang
 * @data 2021/7/5 6:58
 * @description: 验证：死锁 多个线程抢一把锁 造成死锁的情况
 */
public class Deadlock implements Runnable {


    int flag = 1;
    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        Deadlock r1 = new Deadlock();
        Deadlock r2 = new Deadlock();
        r1.flag = 1;
        r2.flag = 0;
        new Thread(r1).start();
        new Thread(r2).start();
    }

    @Override
    public void run() {
        System.out.println("flag = " + flag);
        if (flag == 1) {
            //如果代码走到这行,说明当前线程获取到lock1锁
            synchronized (o1) {
                try {
                    // sleep只会让线程进入休眠状态 但是并不会释放锁
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }
}


/*结论：
 关于死锁的问题
 造成的原因是：线程1已经拥有锁1，还想获取锁2 但是这个时候锁2 已经被线程2占有 但是线程2也想获取到锁1
              所以就导致死锁的问题
*
*
* */